BeautifulSoup 网页抓取,无结果

BeautifulSoup web scraping, no results

我正在尝试从 https://hk.appledaily.com/search/apple 抓取新闻信息。 我需要从 div class="flex-feature" 获取新闻内容,但它只有 return []。希望有大神帮忙,谢谢!

from bs4 import BeautifulSoup
import requests


page = requests.get("https://hk.appledaily.com/search/apple")

soup = BeautifulSoup(page.content, 'lxml')

results = soup.find_all('div', class_ = "flex-feature")


print(results)

如果您在浏览器中查看页面源代码,您会发现 flex-feature 不在 HTML 中。这是服务器在呈现 JavaScript 和所有动态内容之前最初发回的 HTML。这也是 HTML,requests.get 将给你 ([])。

要访问这些元素,您可能需要使用诸如 Selenium that will allow you to automate a browser and render the JavaScript that is dynamically loading the page. Check out my answer to a similar question 之类的东西来获得一些见解!

其他资源:

该页面上的数据是动态获取和呈现的(通过 js)。因此,除非您评估 javascript.

,否则您将无法获取数据

抓取数据的一种方法是使用无头浏览器。
这是一个使用 pyppeteer.

的示例
import asyncio
from pyppeteer import launch

# https://pypi.org/project/pyppeteer/

URL = 'https://hk.appledaily.com/search/apple'

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto(URL)

    await page.waitForSelector(".flex-feature")

    elements = await page.querySelectorAll('.flex-feature')
    
    for el in elements:
        text = await page.evaluate('(el) => el.textContent', el)
        print(text)


    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

输出:

3小時前特朗普確診 不斷更新 特朗普新聞秘書及多名白宮職員確診 「白宮群組」持續擴大特朗普確診 不斷更新

 ... REDUCTED ...